package com.utc.cards.table.jade.agent.rulesAgent;

import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.utc.cards.common.jade.Mapper;
import com.utc.cards.model.deck.Deck;
import com.utc.cards.model.game.IRules;
import com.utc.cards.model.game.Info;
import com.utc.cards.model.game.InfoType;
import com.utc.cards.model.player.Hands;
import com.utc.cards.model.player.IPlayer;

public class InitialCardDistributionBehaviour extends OneShotBehaviour
{

    private static final long serialVersionUID = 4603522248205202385L;
    private static Logger log = LoggerFactory.getLogger(InitialCardDistributionBehaviour.class);

    private RulesAgent agent;

    public InitialCardDistributionBehaviour(RulesAgent rulesAgent)
    {
        super(rulesAgent);
        this.agent = rulesAgent;
    }

    @Override
    public void action()
    {
        log.debug("Distributing cards ...");
        Deck deck = agent.getModel().getGame().getDeck();
        List<IPlayer> players = agent.getModel().getGame().getPlayers();
        IRules rules = agent.getModel().getGame().getRules();
        // distribution des cartes
        final List<Deck> cardDistribution = rules.getInitialCardDistribution(deck, players);

        for (final IPlayer player : agent.getModel().getGame().getPlayers())
        {

            int index = 0;

            log.debug("InitialCardDistributionBehaviour: Sending card to : " + player.getName());

            ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
            Info info = new Info();
            Hands hands = new Hands();
            hands.put(IPlayer.MAIN_HAND, cardDistribution.get(index));

            // mise a jour du modele
            player.setHands(hands.getHands());
            agent.getModel().getPlayerHands().put(player, hands.getHands());

            // envoi des cartes
            try
            {
                info.setType(InfoType.SET_CARDS);

                info.setJson(Mapper.getObjectMapper().writeValueAsString(hands));

                msg.setConversationId("info");
                msg.setContent(Mapper.getObjectMapper().writeValueAsString(info));

                log.debug("InitialCardDistributionBehaviour: Receiver: " + agent.getModel().getPlayersMap().get(player.getName()));
                log.debug(msg.getContent());
                msg.addReceiver(agent.getModel().getPlayersMap().get(player.getName()));
                agent.send(msg);
            }
            catch (JsonProcessingException e)
            {
                log.error("Error while mapping Hands or Info to String");
                e.printStackTrace();
            }
            index++;

        }

        log.debug("Distributing cards DONE");
    }
}